package com.xea.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.apache.commons.io.FileUtils;

import com.gif4j.GifEncoder;

/**
 * @author yhn
 */
public class ImageUtil {
	public static String uploadImage(File file, String src) {
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream(file);
			out = new FileOutputStream(src);
			byte buffer[] = new byte[8192];
			int count = 0;
			while ((count = in.read(buffer)) > 0) {
				out.write(buffer, 0, count);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return src;
	}

	public static String setNewName(String fileName, String fileContentType) {
		String newName = String.valueOf(System.currentTimeMillis());// 当前日期的毫秒格式
		String contentType = fileContentType.substring(fileContentType
				.indexOf("/") + 1, fileContentType.length());
		if (contentType.equals("pjpeg"))
			contentType = "jpg";
		newName = newName + "." + contentType;
		return newName;
	}

	public static File getFixedBoundFile(File srcFile, int height, int width)
			throws Exception {
		File zoomFile = srcFile;
		String filePath = srcFile.getAbsolutePath();
		double Ratio = 0.0;
		if (!srcFile.isFile())
			throw new Exception(srcFile
					+ " is not image file error in getFixedBoundIcon!");
		BufferedImage Bi = ImageIO.read(srcFile);
		if ((Bi.getHeight() > height) || (Bi.getWidth() > width)) {
			if (Bi.getHeight() > Bi.getWidth()) {
				Ratio = (new Integer(height)).doubleValue() / Bi.getHeight();
			} else {
				Ratio = (new Integer(width)).doubleValue() / Bi.getWidth();
			}
			int lastLength = filePath.lastIndexOf(".");
			String subFilePath = filePath.substring(0, lastLength);
			String fileType = filePath.substring(lastLength);
			String newfileType = fileType;
			if (".raw".equals(fileType)) {
				newfileType = ".jpg";
			}
			zoomFile = new File(subFilePath + "_" + height + "_" + width
					+ newfileType);
			Image Itemp = Bi.getScaledInstance(width, height,
					Image.SCALE_SMOOTH);
			AffineTransformOp op = new AffineTransformOp(AffineTransform
					.getScaleInstance(Ratio, Ratio), null);
			Itemp = op.filter(Bi, null);
			try {
				if (".raw".equals(fileType)) {
					ImageIO.write((BufferedImage) Itemp, "jpg", zoomFile);
				} else {
					GifEncoder.encode((BufferedImage) Itemp, zoomFile);
				}
			} catch (Exception ex) {
				System.out.println("######## here error : " + ex);
			}
		}
		return zoomFile;
	}
	
	private static final String PICTRUE_FORMATE_JPG = "jpg";

	public final static void pressImage(String targetImg, String waterImg,
			int x, int y, float alpha) {
		try {
			File file = new File(targetImg);
			Image image = ImageIO.read(file);
			int width = image.getWidth(null);
			int height = image.getHeight(null);
			BufferedImage bufferedImage = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D g = bufferedImage.createGraphics();
			g.drawImage(image, 0, 0, width, height, null);

			Image waterImage = ImageIO.read(new File(waterImg)); // 水印文件
			int width_1 = waterImage.getWidth(null);
			int height_1 = waterImage.getHeight(null);
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
					alpha));

			int widthDiff = width - width_1;
			int heightDiff = height - height_1;
			if (x < 0) {
				x = widthDiff / 2;
			} else if (x > widthDiff) {
				x = widthDiff;
			}
			if (y < 0) {
				y = heightDiff / 2;
			} else if (y > heightDiff) {
				y = heightDiff;
			}
			g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件结束
			g.dispose();
			ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*public static void pressText(String targetImg,String fontName, int fontStyle, int fontSize, Color color, float alpha) {
		String pressText = "华亿传媒";
		int x = Integer.parseInt(XtmdConfig.prop.get("waterImagePressX"));
		int y = Integer.parseInt(XtmdConfig.prop.get("waterImagePressY"));
		try {
			File file = new File(targetImg);

			Image image = ImageIO.read(file);
			int width = image.getWidth(null);
			int height = image.getHeight(null);
			int waterImageWidth = Integer.parseInt(XtmdConfig.prop.get("waterImageWidth"));
			int waterImageHeight = Integer.parseInt(XtmdConfig.prop.get("waterImageHeight"));
			if (width < waterImageWidth || height < waterImageHeight) {
				return;
			}
			BufferedImage bufferedImage = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D g = bufferedImage.createGraphics();
			g.drawImage(image, 0, 0, width, height, null);
			g.setFont(new Font(fontName, fontStyle, fontSize));
			g.setColor(color);
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
					alpha));

			int width_1 = fontSize * getLength(pressText);
			int height_1 = fontSize;
			// int widthDiff = width - width_1;
			// int heightDiff = height - height_1;
			// if (x < 0) {
			// x = widthDiff / 2;
			// } else if (x > widthDiff) {
			// x = widthDiff;
			// }
			// if (y < 0) {
			// y = heightDiff / 2;
			// } else if (y > heightDiff) {
			// y = heightDiff;
			// }

			g.drawString(pressText, width - x - width_1, height - y - height_1);
			g.dispose();
			ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/

	public static int getLength(String text) {
		int textLength = text.length();
		int length = textLength;
		for (int i = 0; i < textLength; i++) {
			if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
				length++;
			}
		}
		return (length % 2 == 0) ? length / 2 : length / 2 + 1;
	}

	public static void resize(String filePath, int height, int width, boolean bb) {
		try {
			double ratio = 0; // 缩放比例
			File f = new File(filePath);
			BufferedImage bi = ImageIO.read(f);
			Image itemp = bi.getScaledInstance(width, height,
					BufferedImage.SCALE_SMOOTH);
			// 计算比例
			if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
				if (bi.getHeight() > bi.getWidth()) {
					ratio = (new Integer(height)).doubleValue()
							/ bi.getHeight();
				} else {
					ratio = (new Integer(width)).doubleValue() / bi.getWidth();
				}
				AffineTransformOp op = new AffineTransformOp(AffineTransform
						.getScaleInstance(ratio, ratio), null);
				itemp = op.filter(bi, null);
			}
			if (bb) {
				BufferedImage image = new BufferedImage(width, height,
						BufferedImage.TYPE_INT_RGB);
				Graphics2D g = image.createGraphics();
				g.setColor(Color.white);
				g.fillRect(0, 0, width, height);
				if (width == itemp.getWidth(null))
					g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
							itemp.getWidth(null), itemp.getHeight(null),
							Color.white, null);
				else
					g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
							itemp.getWidth(null), itemp.getHeight(null),
							Color.white, null);
				g.dispose();
				itemp = image;
			}
			ImageIO.write((BufferedImage) itemp, "jpg", f);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		/*File srcFile1 = new File("d:/pic/m.jpg");
		srcFile1.renameTo(new File("d:/pic/m1.jpg"));
		File srcFile = new File("d:/pic/m1.jpg");
		File destFile = new File("d:/pic/m1.jpg");
		int minWidth = 20;
		int minHeight= 20;
		int pos = 0;
		int offsetX=120;
		int offsetY=60;
		File markFile=  new File("d:/pic/logo.png");
		try {
			imageMark(srcFile, destFile, minWidth, minHeight, pos, offsetX, offsetY, markFile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
	}
	public static int MINWINTH=200;
	public static int MINHEIGHT=150;
	public static int POS=0;
	public static int OFFSETX=120;
	public static int OFFSETY=60;
	public static String MARKFILEPATH = FileUtil.getTomcatPath()+"/hycm/images/logo.png";
	
	public static void imageMark(String filePath) throws IOException{
		File srcFile = new File(filePath);
		File destFile = new File(filePath);
		imageMark(srcFile,destFile,MINWINTH,MINHEIGHT,POS,OFFSETX,OFFSETY,new File(MARKFILEPATH));
	}
	public static void imageMark(File srcFile, File destFile, int minWidth,
			int minHeight, int pos, int offsetX, int offsetY, File markFile)
			throws IOException {
		BufferedImage imgBuff = ImageIO.read(srcFile);
		int width = imgBuff.getWidth();
		int height = imgBuff.getHeight();
		if (width <= minWidth || height <= minHeight) {
			imgBuff = null;
			if (!srcFile.equals(destFile)) {
				FileUtils.copyFile(srcFile, destFile);
			}
		} else {
			imageMark(imgBuff, width, height, pos, offsetX, offsetY, markFile);
			writeFile(imgBuff, destFile);
			imgBuff = null;
		}

	}
	private static void imageMark(BufferedImage imgBuff, int width, int height,
			int pos, int offsetX, int offsetY, File markFile)
			throws IOException {
		Position p = ImageUtil.markPosition(width, height, pos, offsetX,
				offsetY);
		Graphics2D g = imgBuff.createGraphics();
		AlphaComposite a = AlphaComposite.getInstance(AlphaComposite.SRC_ATOP);
		g.setComposite(a);
		g.drawImage(ImageIO.read(markFile), p.getX(), p.getY(), null);
		g.dispose();
	}
	public static void writeFile(BufferedImage imgBuf, File destFile)
		throws IOException {
		File parent = destFile.getParentFile();
		if (!parent.exists()) {
			parent.mkdirs();
		}
		ImageIO.write(imgBuf, "jpeg", destFile);
	}
	
	public static Position markPosition(int width, int height, int p,
			int offsetx, int offsety) {
		/*if (p < 1 || p > 5) {
			p = (int) (Math.random() * 5) + 1;
		}
		int x, y;
		switch (p) {
		// 左上
		case 1:
			x = offsetx;
			y = offsety;
			break;
		// 右上
		case 2:
			x = width + offsetx;
			y = offsety;
			break;
		// 左下
		case 3:
			x = offsetx;
			y = height + offsety;
			break;
		// 右下
		case 4:
			x = width + offsetx;
			y = height + offsety;
			break;
		// 中央
		case 5:
			x = (width / 2) + offsetx;
			y = (height / 2) + offsety;
			break;
		default:
			throw new RuntimeException("never reach ...");
		}*/
		int x, y;
		x = width - offsetx;
		y = height - offsety;
		return new Position(x, y);
	}
	/**
	 * 水印位置
	 * 
	 * 包含左边偏移量，右边偏移量。
	 * 
	 * @author liufang
	 * 
	 */
	public static class Position {
		private int x;
		private int y;

		public Position(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public int getX() {
			return x;
		}

		public void setX(int x) {
			this.x = x;
		}

		public int getY() {
			return y;
		}

		public void setY(int y) {
			this.y = y;
		}
	}
	
	public static void markImage(String filePath){
		markImageByIcon(MARKFILEPATH, filePath, filePath, null);
	}
	
    public static void markImageByIcon(String iconPath, String srcImgPath, 
            String targerPath) { 
        markImageByIcon(iconPath, srcImgPath, targerPath, null); 
    } 
 
    public static void markImageByIcon(String iconPath, String srcImgPath, 
            String targerPath, Integer degree) { 
        OutputStream os = null; 
        try { 
            Image srcImg = ImageIO.read(new File(srcImgPath)); 
 
            
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), 
                    srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB); 
 
            int width = buffImg.getWidth();
    		int height = buffImg.getHeight();
            
            Graphics2D g = buffImg.createGraphics(); 
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg 
                    .getHeight(null), Image.SCALE_SMOOTH), 0, 0, null); 
            if (null != degree) { 
                g.rotate(Math.toRadians(degree), 
                        (double) buffImg.getWidth() / 2, (double) buffImg 
                                .getHeight() / 2); 
            } 
            ImageIcon imgIcon = new ImageIcon(iconPath); 
            Image img = imgIcon.getImage(); 
            float alpha = 1f;  
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha)); 
            g.drawImage(img, width-OFFSETX, height-OFFSETY, null); 
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); 
            g.dispose(); 
            os = new FileOutputStream(targerPath); 
            ImageIO.write(buffImg, "JPG", os); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                if (null != os) 
                    os.close(); 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
        } 
    } 

}
